<?php
// PXFInstance::breakPoint($current_categories);

class ControllerAdmin extends PXFControllerAdmin
{
  /* IMAGES */
  public function images()
  {
		$id = PXFRequest::reqGetOr404('id'); 
		$mod_item = PXFModel::getModel('item');
		$item = $mod_item->find($id);
		PXFRequest::notNullOr404($item); 
		$images = $item->images();
		$result = array();
		foreach($images as $img)
		{
			$result[] = array('id' => $img->id, 'title' => $img->title, 'selected' => ($img->id == $item->image_id));
		}
		echo pxf_json_encode($result);
  }

  public function image_upload()
  {
		/* Required params */
		$itm_id = PXFRequest::reqGetOr404('itm_id'); 

		/* Models */
		$mod_item = PXFModel::getModel('item');
		$mod_images = PXFModel::getModel('item_image');
		$item = $mod_item->find($itm_id);
		PXFRequest::notNullOr404($item); 
		
		$title = new ValidatorSimpleText('title',true);
		$file  = new ValidatorImageFile('image_file',true,array('image/jpeg','image/gif','image/png','image/pjpeg'));
		$validator = PXFValidator::getNew();
		$validator->addItem($title);
		$validator->addItem($file);
		$errors = $validator->validate();

		if(!$errors)
		{
			$image_file = $file->getValue();
			$image = $mod_images->getNew(); 
			$image->title = $title->getValue();
			$image->original = addslashes(resize_image($image_file,250));
			$image->thumbail = addslashes(resize_image($image_file,100));
			$image->item_id = $itm_id;
			$image->user_id = PXFInstance::$user->id;
			$image->save();
		}
  }
  
  public function image_del()
  {
		$img_id = PXFRequest::reqGetOr404('img_id'); 
		$mod_image = PXFModel::getModel('item_image');
		$image = $mod_image->find($img_id);
		$title = rawurldecode($image->title);
		$image->delete();
		echo pxf_json_encode(array('msg' => sprintf('La imagen %s ha sido borrada.',$title)));
	}


  public function image_edit()
  {
		$img_id = PXFRequest::reqGetOr404('img_id'); 
		$title = PXFRequest::reqGetOrDefault('title',''); 
		$mod_images = PXFModel::getModel('item_image');
		$image = $mod_images->find($img_id);
		PXFRequest::notNullOr404($image); 
		$title_old = $image->title;
		$image->title = $title;
		$image->save(array('title'));
		echo pxf_json_encode(array('msg' => sprintf('La imagen %s ha sido renombrada con exito a %s.',$title_old,$image->title))); 
  }

 	public function image_set()
	{ 
		$itm_id = PXFRequest::reqGetOr404('itm_id');
		$img_id = PXFRequest::reqGetOr404('img_id');
		$mod_item = PXFModel::getModel('item');
		$mod_images = PXFModel::getModel('item_image');
		$item  = $mod_item->find($itm_id);
		$image = $mod_images->find($img_id);
		PXFRequest::notNullOr404($item);
		$item->image_id = $img_id;
		$item->save();
		echo pxf_json_encode(array('msg' => sprintf('La imagen %s se ha establecido como predeterminada.',$image->title)));
  }
}
